package controller;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import domain.Contact;
import domain.itf.IDAOContact;

/**
 * Controller class called by ajax to get all contacts
 */
@Controller
@RequestMapping("/GetAllContacts")
public class GetAllContacts {

	@Autowired
	ServletContext servletContext;

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView doGet(HttpServletRequest request, HttpServletResponse response) {
		
		// get the IDAOContact with spring
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		IDAOContact daoContact =(IDAOContact) context.getBean("DAOContact");

		List<Contact> setContact = daoContact.getAllContacts().getContacts();
		if(setContact.size() == 0)
			setContact = null;
		
		ModelAndView view = new ModelAndView("listContact");
		view.addObject("contacts", setContact);
		return view;
	}
}
